package com.google.samples.apps.paging.http

import com.google.gson.Gson
import com.google.samples.apps.library_common.utils.MyHttpLoggingInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * Created by Administrator on 2021/7/10 0010.
 * Describe:
 */

//双重校验锁式-单例 方便直接快速调用简单的接口
val apiService: ApiService by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
    RetrofitClient.getInstance().getApi()
}


class RetrofitClient {
    companion object {
        val BASE_URL = "http://app.zghmy.cn/HuiMei_Web/"

        var retrofitClient: RetrofitClient? = null

        @Synchronized
        fun getInstance(): RetrofitClient {
            if (retrofitClient == null)
                retrofitClient = RetrofitClient()
            return retrofitClient!!
        }
    }


    init {
        //添加一个log拦截器,打印所有的log
        val httpLoggingInterceptor = HttpLoggingInterceptor(MyHttpLoggingInterceptor())
        //可以设置请求过滤的水平,body,basic,headers
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

    }

    var retrofit: Retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(getClient())
        .build()


    fun getApi(): ApiService {
        return retrofit.create(ApiService::class.java)
    }

    private fun getClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(
                HttpLoggingInterceptor(
                    MyHttpLoggingInterceptor()
                ).apply {
                    level = HttpLoggingInterceptor.Level.BODY
                }
            )
            .build()
    }
}